package com.utilities.buffer;

import java.util.Arrays;

public class ArrayBuffer<T> {


    private Object[] array;

    private int postion;


    public ArrayBuffer(int capacity) {
        this.postion = 0;
        this.array = new Object[capacity];
    }

    public void splice(int offset, int len, Object[] data) {

        int delta = data.length - len;
        int src = offset + len;
        int nmoves = postion - src;
        int dst = src + delta;
        int expectSize = postion + delta;

        //need expand
        if (expectSize >= array.length) {

            Object[] newArray=new Object[Math.max(expectSize,2*data.length)];

            System.arraycopy(array,0,newArray,0,offset);
            System.arraycopy(data,0,newArray,offset,data.length);
            System.arraycopy(array,src,newArray,dst,nmoves);
            array=newArray;


        } else {

            System.arraycopy(array,src,array,dst,nmoves);

            System.arraycopy(data,0,array,offset,data.length);
        }

        postion=expectSize;

    }

    @Override
    public String toString(){

        StringBuilder sb=new StringBuilder();
        for(int i=0;i<postion;i++){

            sb.append(array[i]).append(",");

        }
        sb.toString();
        return sb.toString();

    }


    public static void main(String[] args) {


        ArrayBuffer<String> buffer=new ArrayBuffer<>(100);


        buffer.splice(0,0,new String[]{"a","B","c","D"});


        System.out.println(buffer.toString());


        buffer.splice(2,2,new String[]{"x","y","z","xx"});


        buffer.splice(0,buffer.postion,new String[]{"1111xxxx"});


        System.out.println(buffer.toString());
    }

}
